package org.rox.hephantan.bai2;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class Server {
	static DatagramSocket socket;
	public static void main(String[] args) {		
		DatagramPacket packet;
		byte[] buf = new byte[256];
		String data;
		try {			
			socket = new DatagramSocket(1001);
			System.out.println("Server is running..");
			
			//create a datagram packet for receiving packets
			packet = new DatagramPacket(buf, buf.length);
			while (true) {
				socket.receive(packet);
				
				//get data
				buf = packet.getData();				
				data = new String(buf).trim();				
				System.out.println("Data received from Client: " + data);
				
				//get Client's address & port
				InetAddress remoteAddress = packet.getAddress();
				int remotePort = packet.getPort();
				
				//process data, then send it back to Client
				data = data.toUpperCase();				
				send(data.getBytes(), remoteAddress, remotePort);
			}
		} catch(SocketException se) {
			se.printStackTrace();
		} catch(IOException ie) {
			ie.printStackTrace();
		}		
	}
	static void send(byte[] buf, InetAddress remoteAddress, int remotePort) {		
		//create a datagram packet for sending packets
		DatagramPacket packet = new DatagramPacket(buf, buf.length, remoteAddress, remotePort);
		try {
			socket.send(packet);
		} catch(IOException io) {
			io.printStackTrace();
		}
	}
}
